from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.models import User, VSession
from software.models import SoftwareData, SoftwareVersion, SoftwareType
from storehouse.models import Storehouse
from user.dataCheck import DataCheck
import pdb, os
import logging
from conf.sysConfig import config
from software.views.view_software import tolist

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def getDataList(request, *args, **kwargs):
    """
        url    : /need/list/
        method : POST

    :param request:
            page:data.page,
            maxItem:data.maxItem,
            token:data.token,//用户密钥
            softwareGroup:data.softwareGroup,//管理人员 0:所有(包括审核已通过、未通过、未审核) 1：归档
                                            //开发人员 0:所有(包括审核已通过、未通过、未审核)，1：归档

    :return:
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'materialList':[{
                'materialId':null,//资料id
                'softwareName':null,
                'materialName':null,//资料名称
                'versionName':null,//软件版本
                'storehouseName':null,//所属仓库名称
                'userName':null,//资料上传用户
                'uploadTime':null,//资料上传时间
                'softwareDetails':null,//软件描述
                'size':null,//资料大小
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        if requestParam['softwareGroup'] == '0':
            dataList = SoftwareData.objects.filter(isActive=True).order_by('-uploadTime')
            if dataList.exists():
                # pdb.set_trace()
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:

                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()
                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),
                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['softwareGroup'] == '1':
            dataList = SoftwareData.objects.filter(isActive=False).order_by('-uploadTime')
            if dataList.exists():
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:
                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()

                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),

                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
    elif userType == '1':
        if requestParam['softwareGroup'] == '0':
            # pdb.set_trace()
            dataList = SoftwareData.objects.filter(isActive=True, softwareVersion__software__user=user,
                                                   dataCheckState=1)  # order_by('-uploadTime')
            if dataList.exists():
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:
                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()

                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),
                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['softwareGroup'] == '1':
            dataList = SoftwareData.objects.filter(isActive=True, softwareVersion__software__user=user,
                                                   dataCheckState=2).order_by('-uploadTime')
            if dataList.exists():
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:
                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()

                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),
                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['softwareGroup'] == '2':
            dataList = SoftwareData.objects.filter(isActive=True, softwareVersion__software__user=user,
                                                   dataCheckState=0).order_by('-uploadTime')
            if dataList.exists():
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:
                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()

                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),
                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['softwareGroup'] == '3':
            dataList = SoftwareData.objects.filter(isActive=False, softwareVersion__software__user=user).order_by(
                '-uploadTime')
            if dataList.exists():
                dataListNum = len(dataList)
                dataLists = []
                result = dataList[
                         min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

                for data in result:
                    version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()

                    dataList = {
                        'materialId': data.id,
                        'softwareName': version.softwareName,
                        'materialName': data.dataName,
                        'materialState': data.dataCheckState,
                        'versionName': version.version,
                        'storehouseName': version.store.storehouseName,
                        'userName': version.user.name,
                        'uploadTime': data.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'softwareDetails': version.software.softwareDetails,
                        'size': data.file.size,
                        # 'size': tolist(version.file.all(), False),
                    }
                    dataLists.append(dataList)
            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "materialList": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
                # elif userType == '3':
    #     if requestParam['softwareGroup'] == '0':
    #         pdb.set_trace()
    #         dataList = SoftwareData.objects.filter(isActive=True,dataCheckState='1')            
    #         if dataList.exists():
    #             dataListNum = len(dataList)
    #             dataLists = []
    #             result = dataList[min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
    #                                                                                                     requestParam['page'] *
    #                                                                                                     requestParam['maxItem'])]    

    #             for data in result:
    #                 version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()                
    #                 browse = SoftwareVersion.objects.filter(softwareVersion_data=data,isBrowse=user.company)
    #                 if browse.exists():                    
    #                     dataList = {
    #                         'materialId': data.id,
    #                         'softwareName': version.softwareName,
    #                         'materialName': data.dataName,
    #                         'materialState': data.dataCheckState,
    #                         'versionName': version.version,
    #                         'storehouseName': version.store.storehouseName,
    #                         'userName': version.user.name,
    #                         'uploadTime': data.uploadTime,
    #                         'softwareDetails': version.software.softwareDetails,
    #                         'size': version.file.size,
    #                     }
    #                     dataLists.append(dataList)
    #                 else:
    #                     dataList = []

    #         else:
    #             data = {
    #                 "code": 0,
    #                 "msg": "success",
    #                 "totalNum": 0,
    #                 "materialList": [],
    #             }
    #             logger_request.info(data)
    #             return JsonResponse(data)       
    #     elif requestParam['softwareGroup'] == '1':
    #         dataList = SoftwareData.objects.filter(isActive=False,dataCheckState='1')            
    #         if dataList.exists():
    #             dataListNum = len(dataList)
    #             dataLists = []
    #             result = dataList[min(dataListNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(dataListNum,
    #                                                                                                     requestParam['page'] *
    #                                                                                                     requestParam['maxItem'])]    

    #             for data in result:
    #                 version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()                
    #                 browse = SoftwareVersion.objects.filter(softwareVersion_data=data,isBrowse=user.company)
    #                 if browse.exists():                    
    #                     dataList = {
    #                         'materialId': data.id,
    #                         'softwareName': version.softwareName,
    #                         'materialName': data.dataName,
    #                         'materialState': data.dataCheckState,
    #                         'versionName': version.version,
    #                         'storehouseName': version.store.storehouseName,
    #                         'userName': version.user.name,
    #                         'uploadTime': data.uploadTime,
    #                         'softwareDetails': version.software.softwareDetails,
    #                         'size': version.file.size,
    #                     }
    #                     dataLists.append(dataList)
    #                 else:
    #                     dataList = []

    #         else:
    #             data = {
    #                 "code": 0,
    #                 "msg": "success",
    #                 "totalNum": 0,
    #                 "materialList": [],
    #             }
    #             logger_request.info(data)
    #             return JsonResponse(data)
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
            "totalNum": 0,
            "materialList": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": dataListNum,
        "materialList": dataLists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def dataScreen(request, *args, **kwargs):
    """
        inputData:{
            token: data.token, //用户的秘钥
            keyWord:data.keyWord,//关键词
            dataCheckState:data.dataCheckState,//资料状态0：未审核，1：审核通过，2：未通过
            storehouseId:data.storehouseId,
            group:data.group,//0:所有 1：已删除

        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'materialList':[{
                'dataId':null,//资料id
                'softwareName':null,
                'version':null,//软件版本
                'storehouseName':null,//仓库名称
                'username':null,//资料上传用户
                'uploadTime':null,//资料上传时间
                'softwareFunction':null,//软件描述
                // 'datasize':null,//资料大小
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}

    if requestParam['keyWord'] != '':
        filterDict['dataName__icontains'] = requestParam['keyWord']  # to do 关键字描述
    if requestParam['group'] != '':
        if requestParam['group'] == '0':
            filterDict['isActive'] = True
        elif requestParam['group'] == '1':
            filterDict['isActive'] = False
        else:
            data = {
                "code": 0,
                "msg": "Group Error",
                'totalNum': 0,
                'materialList': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['dataCheckState'] != '':
        if requestParam['dataCheckState'] == '0':
            filterDict['dataCheckState'] = '0'
        elif requestParam['dataCheckState'] == '1':
            filterDict['dataCheckState'] = '1'
        elif requestParam['dataCheckState'] == '2':
            filterDict['dataCheckState'] = '2'
        else:
            data = {
                "code": 0,
                "msg": "dataCheckState Error",
                'totalNum': 0,
                'materialList': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['storehouseId'] != None:
        filterDict['softwareVersion__software__store__id'] = requestParam['storehouseId']
    # pdb.set_trace()
    datalist = SoftwareData.objects.filter(**filterDict).order_by('-uploadTime')
    if datalist.exists():
        dataLists = []

        totalNum = len(datalist)

        for data in datalist:
            version = SoftwareVersion.objects.filter(softwareVersion_data=data).first()
            datalist = {
                'materialId': data.id,
                'softwareName': version.softwareName,
                'materialName': data.dataName,
                'materialState': data.dataCheckState,
                'versionName': version.version,
                'storehouseName': version.store.storehouseName,
                'userName': version.user.name,
                'uploadTime': data.uploadTime,
                'softwareDetails': version.software.softwareDetails,
                'size': data.file.size,
                # 'size': tolist(version.file.all(), False),
            }
            dataLists.append(datalist)

        result = dataLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                    requestParam[
                                                                                                        'page'] *
                                                                                                    requestParam[
                                                                                                        'maxItem'])]

    else:
        data = {
            "code": 0,
            "msg": "success",
            'totalNum': 0,
            'materialList': []
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'materialList': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def getStorehouseList(request, *args, **kwargs):
    """
        url    : /software/storehouselist/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'storehouselist':[{
                    'storehouseId':null,//战区id
                    'name':null,//战区名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    storehouselist = Storehouse.objects.all()
    if storehouselist.exists():
        totalNum = len(storehouselist)
        storehouselists = []
        result = storehouselist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                         requestParam[
                                                                                                             'page'] *
                                                                                                         requestParam[
                                                                                                             'maxItem'])]

        for storehouse in result:
            storehouselist = {
                'storehouseId': storehouse.id,
                'name': storehouse.storehouseName,
            }
            storehouselists.append(storehouselist)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "storehouselist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "storehouselist": storehouselists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getType(request, *args, **kwargs):
    """
        url    : /software/typeList/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'sortList':[{
                    'softwareTypeId':null,
                    'softwareType':null,//名称
                    'softwareTypeTime':null,//创建时间
                    'softwareTypeState':null,//0:关闭，1：开启（int类型）
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    softwareTypelist = SoftwareType.objects.filter(isActive=True).order_by('-createTime')
    if softwareTypelist.exists():
        totalNum = len(softwareTypelist)
        softwareTypelists = []
        result = softwareTypelist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                           requestParam[
                                                                                                               'page'] *
                                                                                                           requestParam[
                                                                                                               'maxItem'])]

        for softwareType in result:
            softwareTypelist = {
                'softwareTypeId': softwareType.id,
                'softwareType': softwareType.softwareType,
                'softwareTypeTime': softwareType.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                'softwareTypeState': softwareType.softwareTypeState,
            }
            softwareTypelists.append(softwareTypelist)

    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "sortList": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "sortList": softwareTypelists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def softwareTypeOption(request, *args, **kwargs):
    """
        url    : /software/typeOption/
        method : POST

    :param request:
            token: data.token, // 用户的秘钥
            softwareTypeId:data.softwareTypeId,//0,2
            softwareTypeState:data.softwareTypeState,//2
            softwareType:softwareType,//名称 1,2
            option:data.option,//0:删除，1：新增,2：修改

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        if requestParam['option'] == '0':
            if requestParam['softwareTypeId'] != None:
                softwareType = SoftwareType.objects.get(pk=requestParam['softwareTypeId'])
                softwareType.isActive = False
                softwareType.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'softwareTypeId is Nnone',
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['option'] == '1' and requestParam['softwareType'] != '':
            softwareType = SoftwareType.objects.create(
                softwareType=requestParam['softwareType'],
            )
        elif requestParam['option'] == '2':
            if requestParam['softwareTypeId'] != None:
                if requestParam['softwareType'] != '' and requestParam['softwareTypeState'] == '':
                    softwareType = SoftwareType.objects.get(pk=requestParam['softwareTypeId'])
                    softwareType.softwareType = requestParam['softwareType']
                    softwareType.save()
                elif requestParam['softwareType'] == '' and requestParam['softwareTypeState'] != '':
                    softwareType = SoftwareType.objects.get(pk=requestParam['softwareTypeId'])
                    softwareType.softwareTypeState = requestParam['softwareTypeState']
                    softwareType.save()
                elif requestParam['softwareType'] != '' and requestParam['softwareTypeState'] != '':
                    softwareType = SoftwareType.objects.get(pk=requestParam['softwareTypeId'])
                    softwareType.softwareTypeState = requestParam['softwareTypeState']
                    softwareType.softwareType = requestParam['softwareType']
                    softwareType.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'softwareTypeId is Nnone',
                }
                logger_request.info(data)
                return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)
